package cn.deepmax.spring.cloud.server.api.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

@Slf4j
@Configuration
public class CommonConfig {

    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> {
            String param = exchange.getRequest().getQueryParams().getFirst("user");
            if(StringUtils.hasText(param)){
                return Mono.just(param);
            }else{
                //spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key默认为true
                //则携带这个参数但是值为null将会被deny 默认503错误
                return Mono.empty();
            }
        };
    }

    //这里展示了GlobalFilter 的定义方法和执行顺序
    @Bean
    @Order(-1)
    public GlobalFilter globalFilter1(){
        return ((exchange, chain) -> {
           log.info("[pre]first filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("[post]second filter");
            }));
        });
    }

    @Bean
    @Order(0)
    public GlobalFilter globalFilter2() {
        return (exchange, chain) -> {
            log.info("[pre]second filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("[post]first filter");
            }));
        };
    }
}
